package com.zsh.weather.ln.https

import com.yechaoa.yutilskt.LogUtilKt
import com.zsh.weather.ln.base.BaseResponse
import okhttp3.Call
import okhttp3.Response
import java.io.IOException

abstract class BaseCallBack<T>(var clz: Class<T>) : AbstractCallBack {
    override fun onFailure(call: Call, e: IOException) {
        fail(e.toString())
    }

    override fun onResponse(call: Call, response: Response) {
        try {
            if (call!!.isCanceled()) {
                onFailure(call, IOException("Canceled!"))
                return
            }
            LogUtilKt.d("code_:" + response.code)
            if (response.code !in 200..299) { // 返回Code不在200-299请求失败
                onFailure(call, IOException("request failed , reponse's code is : " + response.code))
                return
            }
            val str = response.body!!.string()
            LogUtilKt.d("response_:" + str)
            var baseResponse = JsonParser.parserBean(str,BaseResponse::class.java)
            if(baseResponse.code != 200){
                LogUtilKt.d("服务器返回错误")
                onFailure(call, IOException("服务器返回错误" ))
                return
            }
            success(call, JsonParser.parserBean(str, clz))
        } catch (e: Exception) {
            onFailure(call, e as IOException)
        } finally {
            if (response.body != null)
                response.body!!.close()
        }
    }

    abstract fun success(call: Call?, data: T)
    abstract fun fail(error: String)
}